using System.Collections.Generic;
using System.Timers;
using OneDayModel.Interfaces;

namespace OneDayModel.Model
{
    public class StatisticsModel
    {
        private readonly IRepository repository;
        private IEnumerable<Statistic> totals;
        private IEnumerable<Statistic> online;
        private IEnumerable<Statistic> newToday;
        private static StatisticsModel instance;
        private static readonly object lockObject = new object();
        private const double interval = 10000;

        public static StatisticsModel GetInstance(IRepository repository)
        {
            if (instance == null)
            {
                lock(lockObject)
                {
                    if (instance == null)
                    {
                        instance = new StatisticsModel(repository);
                    }
                }
            }
            return instance;
        }

        private StatisticsModel(IRepository repository)
        {
            this.repository = repository;
            SetStatistics();
            SetTimer();
        }

        private void SetTimer()
        {
            Timer timer = new Timer(interval);
            timer.Elapsed += delegate(object sender, ElapsedEventArgs e) { SetStatistics(); };
            timer.Enabled = true;
        }

        private void SetStatistics()
        {
            StatisticsStruct statisticsStruct = repository.CollectStatistics();
            totals = statisticsStruct.Totals;
            online = statisticsStruct.Online;
            newToday = statisticsStruct.NewToday;
        }

        public IEnumerable<Statistic> Totals
        {
            get { return totals;}
        }

        public IEnumerable<Statistic> Online
        {
            get { return online;  }
        }

        public IEnumerable<Statistic> NewToday
        {
            get { return newToday; }
        }
    }

    
}